package com.cybertron.lockdown.spider.handler;

import com.alibaba.fastjson.JSON;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.scheduler.QueueScheduler;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiezhouyan on 15-1-20.
 */
public class CountHandler extends Handler {

    public CountHandler(BufferedReader in, PrintWriter out, Spider spider, HandleTask task, HandleRequest request) {
        super(in, out, spider, task, request);
    }

    @Override
    public void execute() {
        QueueScheduler scheduler = (QueueScheduler) spider.getScheduler();
        while (request.isConnected() && !isStoped()) {
            try {
                int leftCount = scheduler.getLeftRequestsCount(null);
                int totalCount = scheduler.getTotalRequestsCount(null);
                Map<String, Object> response = new HashMap<String, Object>();
                response.put("leftCount", leftCount);
                response.put("totalCount", totalCount);
                response.put("time", new Date().getTime());
                task.setResponse(response);
                out.println(JSON.toJSONString(task));
                out.flush();
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
